package com.ohos.fresco.demo;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Window;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.image.PixelMap;

import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.fresco.helper.Phoenix;
import com.facebook.fresco.helper.listener.IResult;
import com.facebook.fresco.helper.utils.DensityUtil;
import com.facebook.fresco.helper.utils.ImageFileUtils;

/**
 * giffirst框架的能力
 *
 * @author dev
 * @date 2021-08-20
 */
public class GIFFirstFrameAbility extends Ability {
    private Image mImageView;
    private Image sdv_1;
    private EventHandler eventHandler;
    private int count = 0;

    @Override
    public void onStart(Intent intent) {
        Window window = getWindow();
        window.setStatusBarColor(Color.getIntColor("#313A99"));
        window.setStatusBarVisibility(Component.VISIBLE);
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_fresco_frame_gif);

        mImageView = (Image) findComponentById(ResourceTable.Id_iv_thumbnail);
        sdv_1 = (Image) findComponentById(ResourceTable.Id_sdv_1);

        ComponentContainer.LayoutConfig layoutConfig1 = mImageView.getLayoutConfig();
        layoutConfig1.width = DensityUtil.vp2px(this, 180);
        layoutConfig1.height = DensityUtil.vp2px(this, 112);
        mImageView.setLayoutConfig(layoutConfig1);
        mImageView.setPixelMap(ImageFileUtils.getPixelMap(getContext(), ResourceTable.Media_icon_dog_and_cat, 0));

        // 手动设置gif图
        ComponentContainer.LayoutConfig layoutConfig = sdv_1.getLayoutConfig();
        layoutConfig.width = DensityUtil.vp2px(this, 100);
        layoutConfig.height = DensityUtil.vp2px(this, 70);
        sdv_1.setLayoutConfig(layoutConfig);
        eventHandler = new EventHandler(EventRunner.getMainEventRunner());
        eventHandler.sendEvent(innerEvent);
    }

    final InnerEvent innerEvent = InnerEvent.get(new Runnable() {
        @Override
        public void run() {
            if (count >= 39) {
                count = 0;
            }
            sdv_1.setPixelMap(ImageFileUtils.getPixelMap(getContext(), ResourceTable.Media_icon_dog_and_cat, count));
            count++;
            eventHandler.sendEvent(InnerEvent.get(this), 20);
        }
    });
    @Override
    protected void onStop() {
        super.onStop();
        if (eventHandler != null) {
            eventHandler.removeAllEvent();
        }
    }
}
